package com.zzl.finance.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzl.finance.order.constant.*;
import com.zzl.finance.order.dao.OrderDao;
import com.zzl.finance.order.dto.*;
import com.zzl.finance.order.dto.feigndto.TicketFinanceOrderDto;
import com.zzl.finance.order.entity.OrderEntity;
import com.zzl.finance.order.entity.OrderInvoiceEntity;
import com.zzl.finance.order.feign.BondsTicketFeign;
import com.zzl.finance.order.service.OrderInvoiceService;
import com.zzl.finance.order.service.OrderService;
import com.zzl.general.common.constant.Constant;
import com.zzl.general.common.exception.SysException;
import com.zzl.general.common.serurity.entity.User;
import com.zzl.general.common.utils.PageUtils;
import com.zzl.general.common.utils.Query;
import com.zzl.general.common.utils.UuidUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author sunpp
 * @date 2021-11-26 19:40:12
 */
@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Autowired
    private OrderInvoiceService orderInvoiceService;

    @Autowired
    private BondsTicketFeign bondsTicketFeign;

    @Override
    public PageUtils queryOrderPage(Map<String, Object> params, User user) {
        /*TODO*/
        return null;
    }

    @Override
    public PlatOrderDetail getPlatOrderDetail(Integer id) throws SysException {
        OrderEntity orderEntity = this.getById(id);
        if (ObjectUtils.isEmpty(orderEntity)) {
            throw new SysException("未查到当前订单");
        }
        PlatOrderDetail detail = new PlatOrderDetail();
        detail.setOrderStatusStr(OrderStatusEnum.getValue(orderEntity.getOrderStatus()));
        detail.setInvoiceStatusStr(InvoiceStatusEnum.getValue(orderEntity.getInvoiceStatus()));
        BeanUtils.copyProperties(orderEntity, detail);
        // 查发票
        List<OrderInvoiceEntity> orderInvoice = orderInvoiceService.getOrderInvoice("id");
//        List<OrderInvoiceEntity> orderInvoice = orderInvoiceService.getOrderInvoice(id);
        if (!CollectionUtils.isEmpty(orderInvoice)) {
            detail.setInvoiceEntity(orderInvoice.get(0));
        }
        return detail;
    }

    @Override
    public OrderDetailDto getOrderDetail(String id) throws SysException {
        OrderDetailDto dto = new OrderDetailDto();
        OrderEntity orderEntity = this.getById(id);
        if (ObjectUtils.isEmpty(orderEntity)) {
            throw new SysException("未找到当前订单");
        }
        BeanUtils.copyProperties(orderEntity, dto);
        dto.setOrderStatusStr(OrderStatusEnum.getValue(orderEntity.getOrderStatus()));
        dto.setInvoiceStatusStr(InvoiceStatusEnum.getValue(orderEntity.getInvoiceStatus()));
        try {
            TicketFinanceOrderDto finance = bondsTicketFeign.getFinanceByTicketNo(orderEntity.getTicketNo());

            if (!ObjectUtils.isEmpty(finance)) {
                dto.setFinanceOrderDto(finance);
            }
        } catch (Exception e) {
            throw new SysException("融资服务：融资信息异常");
        }
        return dto;
    }

    /**
     * 分页查询
     *
     * @param params 查询参数
     * @return 分页数据
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        LambdaQueryWrapper<OrderEntity> queryWrapper = new LambdaQueryWrapper<>();
        Object startTime = params.get("startTime");
        Object endTime = params.get("endTime");
        Object keywords = params.get("keywords");
        if (!ObjectUtils.isEmpty(startTime)) {
            queryWrapper.apply("date_format(create_time,'%Y-%m-%d') >= str_to_date({0},'%Y-%m-%d')", startTime);
        }
        if (!ObjectUtils.isEmpty(endTime)) {
            queryWrapper.apply("date_format(create_time,'%Y-%m-%d') <=str_to_date({0},'%Y-%m-%d')", endTime);
        }
        queryWrapper.and(!ObjectUtils.isEmpty(keywords), x -> x.like(OrderEntity::getOrderNo, String.valueOf(keywords)).or().like(OrderEntity::getFinanceNo, String.valueOf(keywords)));

        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                queryWrapper
        );
        if (CollectionUtils.isEmpty(page.getRecords())) {
            return new PageUtils(page);
        }
        for (OrderEntity entity : page.getRecords()) {
            entity.setOrderTypeStr(OrderTypeEnum.getValue(entity.getOrderType()));
        }

        return new PageUtils(page);
    }

    @Override
    public void updateStatus(OrderUpdateDto updateDto, User user) {
        UpdateWrapper<OrderEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(OrderEntity::getTicketNo, updateDto.getTicketNo())
                .set(OrderEntity::getOrderStatus, updateDto.getOrderStatus())
                .set(OrderEntity::getUpdaterId, user.getId());
        this.update(updateWrapper);
    }

    /**
     * 新增
     *
     * @param orderAddDto 新增实体
     * @param user        当前登录用户
     * @throws SysException 业务异常
     */
    @Override
    public void saveOrder(OrderAddDto orderAddDto, User user) throws SysException {
        OrderEntity orderEntity = new OrderEntity();
        BeanUtils.copyProperties(orderAddDto, orderEntity);
        orderEntity.setCreatorId(user.getId());
        orderEntity.setOrderNo(UuidUtils.UUID());
        orderEntity.setOrderType(OrderTypeEnum.LATEST.getCode());
        orderEntity.setOrderAmount(orderAddDto.getSellAmount());
        orderEntity.setOrderStatus(OrderStatusEnum.UNPAID.getCode());
        orderEntity.setInvoiceStatus(InvoiceStatusEnum.INVOICE_ING.getCode());
        orderEntity.setEnterpriseId(user.getEnterpriseId());
        orderEntity.setChainAddress("ORDER" + UuidUtils.UUID());
        orderEntity.setOrgId(user.getOrgId());
        if (!this.save(orderEntity)) {
            throw new SysException("A00001", "保存失败！");
        }
    }

    /**
     * 修改
     *
     * @param orderUpdateDto 修改实体
     * @param user           当前登录用户
     * @throws SysException 业务异常
     */
    @Override
    public void updateOOrderById(OrderUpdateDto orderUpdateDto, User user) throws SysException {
        OrderEntity orderEntity = new OrderEntity();
        BeanUtils.copyProperties(orderUpdateDto, orderEntity);
        orderEntity.setUpdaterId(user.getId());
        if (!this.updateById(orderEntity)) {
            throw new SysException("A00002", "修改失败！");
        }
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void invoiceCheckSubmit(CheckSubmit checkSubmit, User user) throws SysException {
        if (checkSubmit.getCheckResult().equals(0) && ObjectUtils.isEmpty(checkSubmit.getCheckResult())) {
            throw new SysException("审批驳回 备注不能为空");
        }
        OrderEntity orderEntity = this.getById(checkSubmit.getId());
        if (ObjectUtils.isEmpty(orderEntity)) {
            throw new SysException("未找到订单信息");
        }
        // 审批通过
//        List<OrderInvoiceEntity> orderInvoice = orderInvoiceService.getOrderInvoice(checkSubmit.getId());
        List<OrderInvoiceEntity> orderInvoice = orderInvoiceService.getOrderInvoice("");
        OrderInvoiceEntity invoiceEntity = orderInvoice.get(0);
        if (checkSubmit.getCheckResult().equals(StringConstant.YES)) {
            invoiceEntity.setInvoiceStatus(InvoiceStatusEnum.INVOICE.getCode());
        } else {
            invoiceEntity.setInvoiceStatus(InvoiceStatusEnum.INVALID_VOIDED.getCode());
        }
        invoiceEntity.setUpdaterId(user.getId());

        orderEntity.setInvoiceStatus(InvoiceStatusEnum.INVOICE.getCode());
        orderEntity.setUpdateTime(new Date());
        orderEntity.setUpdaterId(user.getId());
        this.updateById(orderEntity);
        orderInvoiceService.updateById(invoiceEntity);
    }

    /**
     * 修改发票信息
     *
     * @param dto  参数
     * @param user 登录用户
     * @throws SysException 业务异常
     */
    @Override
    public void updatePlatOrder(OrderInvoiceUpdateDto dto, User user) throws SysException {
        if (ObjectUtils.isEmpty(dto.getId())) {
            throw new SysException("参数错误，请传入发票id");
        }
        OrderInvoiceEntity entity = orderInvoiceService.getById(dto.getId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new SysException("未查到当前数据");
        }
        BeanUtils.copyProperties(dto, entity);
        entity.setUpdaterId(user.getId());
        entity.setUpdateTime(new Date());
        orderInvoiceService.updateById(entity);
    }

    @Override
    public void saveEntity(OrderEntity orderEntity) {
        this.save(orderEntity);
    }

    @Override
    public Double getTotalConsumption(String enterpriseId) {
        return baseMapper.getTotalConsumption(enterpriseId);
    }

}